/*
*初始化 流水号码表
 */
package main

import (
	// "net/http"
	// "encoding/json"
	// "strconv"
	// "time"
	// "github.com/dgrijalva/jwt-go"
	// "github.com/labstack/echo"

	"regexp"

	"gopkg.in/mgo.v2/bson"
	// "github.com/jinzhu/gorm"
	"oxy_server/model"
	"oxy_server/module/log"
)

type (
	SkuColor struct {
		ID           bson.ObjectId `json:"_id" bson:"_id"`
		SkuColorDesc string        `json:"skucolordesc" bson:"skucolordesc"`
		SkuColorCode string        `json:"skucolorcode" bson:"skucolorcode"`
	}
	SkuSize struct {
		ID          bson.ObjectId `json:"_id" bson:"_id"`
		SkuSizeDesc string        `json:"skusizedesc" bson:"skusizedesc"`
		SkuSizeCode string        `json:"skusizecode" bson:"skusizecode"`
	}
)

var colorMap map[string]string
var sizeMap map[string]string

func getColor() error {
	model.DB().Dbname = "OxyDic"
	model.DB().Document = "sku_color"
	query, _, err := model.DB().Query(bson.M{}, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		return err
	}
	colorList := []SkuColor{}
	query.All(&colorList)
	var Map map[string]string
	Map = make(map[string]string)
	for _, item := range colorList {
		Map[item.SkuColorCode] = item.SkuColorDesc
	}
	colorMap = Map
	return nil
}

func getSize() error {
	model.DB().Dbname = "OxyDic"
	model.DB().Document = "sku_size"
	query, _, err := model.DB().Query(nil, 0, 0)
	if err != nil {
		log.Error("查询出错", err)
		return err
	}
	sizeList := []SkuSize{}
	query.All(&sizeList)
	var Map map[string]string
	Map = make(map[string]string)
	for _, item := range sizeList {
		Map[item.SkuSizeCode] = item.SkuSizeDesc
	}
	sizeMap = Map
	return nil
}

func getValue(sku string, t string) string {
	switch t {
	case "color":
		str := sku[len(sku)-4 : len(sku)-1]
		if getLength(str) == 2 {
			if len(sku) == 12 {
				return colorMap[sku[len(sku)-3:len(sku)-1]]
			} else {
				return colorMap[sku[len(sku)-4:len(sku)-2]]

			}
		} else {
			return colorMap[sku[len(sku)-4:len(sku)-1]]
		}
		break
	case "size":
		str := sku[len(sku)-4 : len(sku)-1]
		if getLength(str) == 2 && len(sku) == 13 {
			return sizeMap[sku[len(sku)-2:len(sku)-1]]
		} else {
			return sizeMap[sku[len(sku)-1:len(sku)]]
		}
		break
	}
	return ""
}

func getLength(str string) int {
	var rCharacter = regexp.MustCompile("[a-zA-Z]")
	character := len(rCharacter.FindAllStringSubmatch(str, -1))
	return character
}

func main() {

	err := getColor()
	err = getSize()
	if err != nil {
		log.Error("查询出错", err)
		return
	}
	log.Info("colorList", colorMap)
	log.Info("sizeList", sizeMap)

	log.Info("size", getValue("C1MBJ0171C014", "size"))
	log.Info("color", getValue("C1MBJ0171C014", "color"))
}
